package com.le.basic.linked.singleDemo;

import java.util.Stack;

/**
 * 判断一个链表是否为回文结构 【题目】 给定一个链表的头节点head，请判断该链表是否为回 文结构。
 * 例如： 1->2->1，返回true。 1->2->2->1，返回true。
 * 15->6->15，返回true。 1->2->3，返回false。
 * 进阶： 如果链表长度为N，时间复杂度达到O(N)，额外空间复杂度达到O(1)。
 */
public class QuestionDemo2 {
    public static void main(String[] args) {
        singleLinked link = new singleLinked();
        link.add(new SingleNode(1));
        link.add(new SingleNode(2));
        link.add(new SingleNode(3));

        link.add(new SingleNode(3));
        link.add(new SingleNode(2));
        link.add(new SingleNode(1));
//        boolean flag = judge1(link.getHead());
        boolean flag = judge2(link.getHead());
        System.out.println(flag);
    }

    // 第一种方案: 直接入栈 need n extra space
    private static boolean judge1(SingleNode head) {
        if (head == null || head.next == null){
            return false;
        }
        SingleNode temp = head;
        Stack<Integer> stack = new Stack<>();
        while (temp != null){
            stack.push(temp.data);
            temp = temp.next;
        }
        temp = head;
        while (!stack.isEmpty()){
            if (stack.peek() != temp.data){
                return false;
            }
            stack.pop();
            temp = temp.next;
        }
        return true;
    }

    // 第二种方案: need n/2 extra space, 后半段入栈
    private static boolean judge2(SingleNode head){
        if (head == null || head.next == null){
            return false;
        }
        SingleNode right = head.next;
        SingleNode cur = head;
        while (cur.next != null && cur.next.next != null){
            right = right.next;
            cur = cur.next.next;
        }
        Stack<Integer> stack = new Stack<>();
        while (right != null){
            stack.push(right.data);
            right = right.next;
        }
        while (!stack.isEmpty()){
            if (head.data != stack.pop()){
                return false;
            }
            head = head.next;
        }
        return true;
    }

    // 第三种方案: 后半段逆序, need o(1) extra space
    private static boolean judge3(SingleNode head){
        if (head == null || head.next == null){
            return false;
        }

        return true;
    }

}
